package com.example.demo.controller;

import com.example.demo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/hello") // 浏览器中输入localhost:3080/hello 找到HelloController这个类
public class HelloController {
    // 浏览器中输入localhost:3080/hello/sayHello 找到HelloController这个类下的sayHello这个方法
    @RequestMapping("sayHello")
    @ResponseBody  // 讲return里的内容原封不动的放回到浏览器页面上
    public String sayHello() {
        return "this is from HelloController";
    }

    @RequestMapping("toSuccess")
    public String toSuccess(Model m) {
        //加入模型
        m.addAttribute("name","江苏海洋大学");
        m.addAttribute("msg","欢迎报考");
        // 因为没有@ResponseBody 不回直接输出“mobang”, 而是去找classpath:/templates/目录下对应的html文件
        return "moban";
    }

    @RequestMapping(value = "toHello*",params ={"password","name!=tom"},method = RequestMethod.POST) //url必须带参数name 如： ?name=tom
    public String toHello() {
        return "hello";
    }

    @RequestMapping("showSqr/{val}")
    // 参数从url中传入获取
    public ModelAndView showSqr(@PathVariable("val") Integer val) {
        Integer result = val*val;
        ModelAndView mv = new ModelAndView();
        //跳转到的视图层html名字
        mv.setViewName("result");
        mv.addObject("val",val);
        mv.addObject("result",result);
        return mv;
    }

    @RequestMapping(value = "user/{id}",method = RequestMethod.GET)
    public ModelAndView getUserById(@PathVariable("id") Integer id){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("user");
        User user = User.findById(id);
        mv.addObject("user",user);
        return mv;

    }

    @RequestMapping(value = "user/{id}",method = RequestMethod.POST)
    public ModelAndView updateUserById(@PathVariable("id") Integer id){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("updateUser");
        User user = User.findById(id);
        user.setName("潇洒哥");
        mv.addObject("user",user);
        return mv;

    }
}
